﻿using System;
using System.Windows.Forms;
using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;
using Moe.ECamel.Common.Entities;

namespace Moe.ECamel.Client.WinForms.Forms
{
	public partial class RentalAdvancedForm : ECamelForm
	{
		private readonly ItemsController _controller;
		private readonly Item _item;


		public RentalAdvancedForm()
		{
			InitializeComponent();
		}
		public RentalAdvancedForm(ItemsController controller, Item item)
			:this()
		{
			this._controller = controller;
			this._item = item;
		}

		private void CancallationButton_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}
		private void ConfirmationButton_Click(object sender, EventArgs e)
		{
			Rental rental = null;
			if (TransferFromOtherLibraryCheckBox.Checked)
				rental = TransferCopy();

			if (rental == null && RequestNewCopyCheckBox.Checked)
				rental = RequestNewCopy();
			if (rental == null && RequestReservationCheckBox.Checked)
				RequestReservation();

			if (rental == null)
				this.DialogResult = DialogResult.Cancel;
			else
			{
				ECamelHelper.ShowMessage(MessageIds.RentalSuccessful, rental.ExpectedReturnDate.ToShortDateString());
				this.DialogResult = DialogResult.OK;
			}

			this.Close();
		}

		private Rental TransferCopy()
		{
			var transferResponse = _controller.TransferCopy(_item);

			if (!transferResponse.IsSuccessful)
			{
				ECamelHelper.ShowMessage(MessageIds.InventoryTrasferFailed);
				return null;
			}

			ECamelHelper.ShowMessage(MessageIds.InventoryTrasferSucceeded, transferResponse.ItemTitle,
				transferResponse.ItemCatalogNumber, transferResponse.SourceLibraryName, transferResponse.TargetLibraryName);
			var rentalResponse = _controller.RentItem(_item);
			if (rentalResponse.Error != null)
			{
				ECamelHelper.ShowMessage(rentalResponse.Error);			
				return null;				
			}
			
			return rentalResponse.Rental;
		}
		private Rental RequestNewCopy()
		{
			var requestNewCopyResponse = _controller.RequestNewCopy(_item);
			ECamelHelper.ShowMessage(requestNewCopyResponse);
			if (requestNewCopyResponse.MessageId != MessageIds.InventoryNewCopyAdded)
				return null;

			var rentalResponse = _controller.RentItem(_item);
			if (rentalResponse.Error != null)
			{
				ECamelHelper.ShowMessage(rentalResponse.Error);
				return null;
			}

			return rentalResponse.Rental;
		}
		private void RequestReservation()
		{
			_controller.AddItemReservation(_item);
			ECamelHelper.ShowMessage(MessageIds.RentalReservationRequestAdded);
		}
	}
}
